package user_login

import (
	"benkendSystem/database"
	"benkendSystem/define"
	"benkendSystem/helper"
	"benkendSystem/models"
	"benkendSystem/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// ValidateUser 验证用户密码
func ValidateUser(username, password string) (string, error) {

	var dbPassword string
	err := database.DB.Model(new(models.User)).Select("password").Where("username = ?", username).Find(&dbPassword).Error
	if err != nil {
		return "系统错误", err
	}
	err = utils.CompareHashAndPassword(dbPassword, password)
	if err != nil {
		return "用户名和密码错误", err
	}
	return "ok", nil
}

// GetUserInfo 获取用户信息
func GetUserInfo(username string) (UserInformation, error) {
	data := new(UserInformation)
	userInfo := new(UserInfo)
	err := database.DB.Model(new(models.User)).Select("id,username,realname").Where("username = ?", username).First(&userInfo).Error
	if err != nil {
		return UserInformation{}, err
	}
	departInfo := new(DepartInfo)
	err = database.DB.Model(new(models.Department)).Select("department.id, department.name").Joins("left join user_depart ud on ud.depart_id=department.id").Where("user_id = ?", userInfo.ID).Find(&departInfo).Error
	if err != nil {
		return UserInformation{}, err
	}
	roleInfo := new(RoleInfo)
	err = database.DB.Model(new(models.Role)).Select("role.id,role.name,role.is_admin").Joins("left join user_role ur on ur.role_id=role.id").Where("user_id = ?", userInfo.ID).Find(&roleInfo).Error
	if err != nil {
		return UserInformation{}, err
	}

	data.UserInfo = *userInfo
	data.DepartInfo = *departInfo
	data.RoleInfo = *roleInfo
	return *data, nil
}

// Login 用户登录
func Login(c *gin.Context) {
	in := new(UserLogin)
	err := c.ShouldBindJSON(in)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "参数错误",
		})
		return
	}
	// 校验用户名和密码
	un := utils.ValidateUsername(in.Username)
	pd := utils.ValidatePassword(in.Password)
	if !un {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户名长度必须大于3",
		})
		return
	}
	if !pd {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码长度必须大于8，且必须由大小写字母、数字、特殊字符组成",
		})
		return
	}
	// 验证密码并获取用户信息
	str, err := ValidateUser(in.Username, in.Password)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  str,
		})
		return
	}
	// 获取用户信息
	data, err := GetUserInfo(in.Username)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  err.Error(),
		})
		return
	}
	//var menuList []int64
	//for _, v := range data.MenuInfo {
	//	menuList = append(menuList, v.ID)
	//}
	// 生成token
	token, err := helper.GenerateToken(data.UserInfo.ID, data.RoleInfo.ID, data.RoleInfo.IsAdmin, define.TokenExpire)
	fmt.Println(define.TokenExpire)
	responseData := &UserInformationReply{
		UserID:     strconv.FormatUint(uint64(data.UserInfo.ID), 10),
		UserName:   data.UserInfo.Username,
		RealName:   data.UserInfo.Realname,
		DepartID:   strconv.FormatUint(uint64(data.DepartInfo.ID), 10),
		DepartName: data.DepartInfo.Name,
		RoleID:     strconv.FormatUint(uint64(data.RoleInfo.ID), 10),
		RoleName:   data.RoleInfo.Name,
		IsAdmin:    data.RoleInfo.IsAdmin,
	}
	c.JSON(http.StatusOK, gin.H{
		"code":   200,
		"msg":    "登录成功",
		"result": responseData,
		"token":  token,
	})
}
